<template>
    <el-upload v-model:file-list="fileList" :list-type="listType" :auto-upload="true" :http-request="httpRequest"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-error="handleError"
        :on-success="handleSuccess" :before-upload="beforeUpload" :limit="maxCount" :on-exceed="handleExceed"
        v-bind="$attrs">
        <!-- <template v-if="listType != 'text'">
            <el-icon>
                <Plus />
            </el-icon>
        </template>
<template v-else>
            <el-button type="primary">点击上传</el-button>
        </template> -->
        <template v-for="(_, name) in $slots" #[name]="scope">
            <slot :name="name" v-bind="scope" />
        </template>
    </el-upload>

    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>

<script setup>
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
    maxCount: { type: Number, default: 20 },
    maxSize: { type: Number, default: 2 }, // MB
    accept: { type: String, default: 'image/*' },
    listType: { type: String, default: 'picture-card' },
})

const emit = defineEmits(['change'])
const value = defineModel()
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// watchEffect(() => {
//     fileList.value = value.value
// })

watch(() => value.value, (val) => {
    fileList.value = val
    console.log('watch', val);
}, { immediate: true, deepth: true })


// 文件上传前校验
const beforeUpload = (file) => {
    console.log('beforeUpload', file);
    console.log('isImage', props.accept.split(','));
    // 根据accept属性判断文件类型
    const isImage = props.accept.split(',').some(type => file.type.startsWith(type))
    const isLtSize = file.size / 1024 / 1024 < props.maxSize
    if (!isImage) {
        ElMessage.error(`只能上传${props.accept.replace(/,/g, '、')}文件!`)
        return false
    }
    if (!isLtSize) {
        ElMessage.error(`图片大小不能超过 ${props.maxSize}MB!`)
        return false
    }
}

// 处理文件数量超出限制
const handleExceed = () => {
    ElMessage.warning(`最多只能上传 ${props.maxCount} 张图片`)
}

// 上传请求处理
const httpRequest = async (config) => {
    const { file, onProgress, onSuccess, onError } = config

    // 模拟上传进度
    // const progressInterval = setInterval(() => {
    //     const percent = Math.min(100, (onProgress?.percent || 0) + 10)
    //     onProgress?.({ percent })
    //     if (percent >= 100) clearInterval(progressInterval)
    // }, 200)

    try {
        // 模拟请求（生产环境应替换为真实API）
        const res = await new Promise((resolve) => {
            setTimeout(() => {
                if (Math.random() > 0.5) {
                    resolve({
                        code: 200,
                        data: {
                            url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
                            uid: file.uid,
                            name: file.name
                        }
                    })
                } else {
                    resolve({
                        code: 500,
                        message: '上传失败'
                    })
                }
            }, 1000)
        })
        console.log('res', res);

        if (res.code === 200) {
            value.value = [...value.value, res.data]
            onSuccess(res.data)
            return res.data
        }
        onError('上传失败')
    } catch (error) {
        onError('上传失败:' + error)
    } finally {
        // clearInterval(progressInterval)
    }
}

// 文件删除处理
const handleRemove = (uploadFile, uploadFiles) => {
    console.log('handleRemove', uploadFile, uploadFiles);
    if (uploadFile.status == 'ready') {
        return
    }

    fileList.value = uploadFiles
    value.value = value.value.filter(file => file.uid !== uploadFile.uid)
    ElMessage.success(`删除成功`)
}

// 错误处理增强
const handleError = (error, uploadFile, uploadFiles) => {
    // fileList.value = uploadFiles
    // value.value = value.value.filter(file => file.uid !== uploadFile.uid)
    ElMessage.error(`上传失败`)
}

// 成功处理（添加类型提示）
const handleSuccess = (response) => {
    // fileList.value = fileList.value.filter(file => file.uid !== response.uid)
    // value.value = value.value.filter(file => file.uid !== response.uid)
}

const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}
</script>